package com.vincent.utils;

import java.util.Iterator;
import java.util.NoSuchElementException;

/**
 * Created by wensen on 2016/12/9.
 * 自定义泛型队列
 * implement according to 《Algorithm 4》
 */
public class MyQueue<T> implements Iterable<T>{

    private Node<T> first;
    private Node<T> last;
    private int n;

    private static class Node<T> {
        private T item;
        private Node<T> next;
    }

    public MyQueue() {
        first = null;
        last  = null;
        n = 0;
    }

    public boolean isEmpty() {
        return first == null;
    }

    public int size() {
        return n;
    }

    public T peek() {
        if (isEmpty()) return null;
        return first.item;
    }

    public T dequeue() {

        if (isEmpty()) return null;
        T item = first.item;
        first = first.next;
        n--;
        if (isEmpty()) last = null;
        return item;
    }

    public void enqueue(T item) {
        Node<T> lodLast = last;
        last = new Node<T>();
        last.item = item;
        last.next = null;
        if (isEmpty()) first = last;
        else           lodLast.next = last;
        n++;
    }

    public String toString() {
        StringBuilder s = new StringBuilder();
        for (T item : this) {
            s.append(item);
            s.append(' ');
        }
        return s.toString();
    }

    public Iterator<T> iterator()  {
        return new ListIterator<T>(first);
    }

    private class ListIterator<T> implements Iterator<T> {
        private Node<T> current;

        public ListIterator(Node<T> first) {
            current = first;
        }

        public boolean hasNext()  { return current != null;                     }
        public void remove()      { throw new UnsupportedOperationException();  }

        public T next() {
            if (!hasNext()) throw new NoSuchElementException();
            T item = current.item;
            current = current.next;
            return item;
        }
    }
}
